﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.ObjectBuilder2;

namespace IoCNamed.UnityNameResolver
{
    internal class ResolveNameBuilderStrategy : BuilderStrategy
    {
        private NamedTypeBuildKey ReplaceBuildKeyName(IBuilderContext context, NamedTypeBuildKey buildKey)
        {
            IResolveNamePolicy policy = context.Policies.Get<IResolveNamePolicy>(buildKey);

            if (policy != null)
            {
                return new NamedTypeBuildKey(buildKey.Type, policy.ResolveName(buildKey));
            }

            return buildKey;
        }

        public override void PreBuildUp(IBuilderContext context)
        {
            if (context.BuildKey is NamedTypeBuildKey)
            {
                context.BuildKey = ReplaceBuildKeyName(context, (NamedTypeBuildKey)(context.BuildKey));
            }
        }

        public ResolveNameBuilderStrategy()
            : base()
        {
        }
    }
}
